<script setup>
import { defineAsyncComponent, onMounted, ref } from 'vue';

import { Edit } from '@element-plus/icons-vue';

import { constants } from '#/constant';
import province from '#/tools/index.ts';

// import { areaList } from "@/api/admin/area";
// import { DeptList } from "@/api/organizationalStructure/accountSet";
import { requestApi } from '#/api';
import { imgUrl } from '#/UrlsConfig';
import { getNameById, getProvinces } from '#/utils';

const props = defineProps({
  option: {
    type: Object,
    default: () => {},
  },
});
const UploadImg = defineAsyncComponent(
  () => import('#/component/Upload/Img.vue'),
);
// const Map3D = defineAsyncComponent(() => import("#/component/3DMap/index.vue"));
const UploadImgs = defineAsyncComponent(
  () => import('#/component/Upload/uploadImg.vue'),
);

const aboutFiledId = ref('');

// 解析动态显示条件
const getDisplaySet = (displaySet) => {
  if (displaySet !== undefined && typeof displaySet === 'object') {
    switch (displaySet.method) {
      case '=': {
        return props.option.data[displaySet.name] === displaySet.value;
      }
    }
  }
  return true;
};

/* ==============下拉选择框===============  */
const changeSelect = (val) => {
  console.log(val);
};
const getName = (text, listName) => {
  return getNameById(text, constants[listName]);
};

/* ==============数字输入框===============  */
// 数字格式化
const formatNumber = (value, precision) => {
  return value && value.toFixed(precision);
};

/* ==============选择坐标===============  */
const showMap = ref(false);
const openMap = () => {
  showMap.value = true;
};

/* ==============下拉选择框（树）===============  */
const deptTreeData = ref([]);
const areaData = ref([]);
const equipmentTreeData = ref([]);
const getTreeData = (dataType) => {
  switch (dataType) {
    case 'area': {
      if (areaData.value.length === 0) {
        // areaList().then((res) => {
        //   areaData.value = res.data;
        // });
      }
      break;
    }
    case 'dept': {
      if (deptTreeData.value.length === 0) {
        // DeptList().then((res) => {
        //   deptTreeData.value = res.data;
        // });
      }
      break;
    }
    case 'deviceType': {
      if (equipmentTreeData.value.length === 0) {
        requestApi('/energy-device/deviceType/pageList', {
          current: 1,
          size: 10_000,
          level: 1,
          deviceType: 'DEVICE_TYPE',
        }).then((res) => {
          equipmentTreeData.value =
            (res.data &&
              res.data.records &&
              res.data.records.length > 0 &&
              res.data.records) ||
            [];
        });
      }
      break;
    }
  }
};
const treeData = (dataType) => {
  switch (dataType) {
    case 'area': {
      return areaData.value;
    }
    case 'dept': {
      return deptTreeData.value;
    }
    case 'deviceType': {
      return equipmentTreeData.value;
    }
  }
};

/* ==============图片上传===============  */
// 图片上传
const handleSuccess = (info, prop, propList) => {
  // console.log('handleSuccess', info, prop, propList);
  // props.option.data[propList] = info?.map(item => ({
  //     fileName: item.originalFileName,
  //     fileUrl: item.fileName,
  //     status: item.status,
  //     uid: item.uid,
  // }))
  props.option.data[propList] = JSON.stringify(info);
};

// 图片上传
const imgSuccess = (data, prop) => {
  props.option.data[prop] = imgUrl + data.fileName;
};

// 图片删除
const handleRemove = (info, prop, propList) => {
  // console.log('handleRemove', info, props.option.data[propList]);
  // const findIndex = props.option.data[propList]?.findIndex(item => item.fileUrl == info.fileName);
  // if (findIndex > -1) {
  //   props.option.data[propList].splice(findIndex, 1);
  // }
  props.option.data[propList] = JSON.stringify(info);
};

const onTreeChange = (node, item, data) => {
  console.log('onTreeChange', node, item, data);
  // 关联了需要修改得字段执行下面方法
  if (item?.inputSet?.changeField && node.id != data[item.prop]) {
    // 清空changeFiled对应得字段值
    const changeField = item.inputSet?.changeField;
    if (typeof changeField !== 'string') {
      // 获取value值
      const valueFieldList = Object.values(changeField);
      for (const item of valueFieldList) {
        console.log(item);
        props.option.data[item] = props.option.dataModel[item];
      }
      console.log(props.option.data);
    }
  }
};

// 初始化
onMounted(() => {
  // fetchDangerSourceData();
  // option.items
  if (
    props.option.items !== undefined &&
    typeof props.option.items === 'object'
  ) {
    props.option.items.map((item) => {
      if (item.inputSet.type === 'treeSelect') {
        getTreeData(item.inputSet.source);
      } else if (item.default) {
        props.option.data[item.prop] = item.default;
      }
    });
  }
});
// 字体
const sizeDefault = ref('default');

const imgViewVisible = ref(false);
const imgViewUrl = ref('');
const imgViewIndex = ref(0);
</script>

<template>
  <el-descriptions
    :column="option.columnCount || 3"
    :size="sizeDefault"
    border
    class="el-details"
    title=""
  >
    <template v-for="(item, index) in option.items">
      <el-descriptions-item
        v-if="item.display && item.inputSet.type != 'none'"
        :key="index"
        :span="item.span || 1"
        class-name="desc-item"
        label-class-name="desc-label"
      >
        <template v-if="getDisplaySet(item.displaySet)" #label>
          <div class="cell-item">
            <span v-if="item.rules.required" style="color: red">*</span
            >{{ item.label }}
          </div>
        </template>
        <el-form-item
          v-if="getDisplaySet(item.displaySet)"
          :prop="item.prop"
          label=""
        >
          <!--文本框-->
          <el-input
            v-if="option.editStatus && item.inputSet.type === 'input'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :placeholder="item.rules.message"
            clearable
          />
          <span v-if="!option.editStatus && item.inputSet.type === 'input'">{{
            option.data[item.view || item.prop] || '--'
          }}</span>
          <!-- 文本域 -->
          <el-input
            v-if="option.editStatus && item.inputSet.type === 'textarea'"
            v-model="option.data[item.prop]"
            :autosize="{ minRows: 5, maxRows: 5 }"
            :disabled="item.disabled || false"
            :placeholder="item.rules.message"
            clearable
            type="textarea"
          />
          <span
            v-if="!option.editStatus && item.inputSet.type === 'textarea'"
            style="overflow-wrap: anywhere"
            v-html="
              (option.data[item.view || item.prop] || '--').replace(
                /\n/g,
                '<br>',
              )
            "
          ></span>
          <!--链接-->
          <el-input
            v-if="option.editStatus && item.inputSet.type === 'link'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :placeholder="item.rules.message"
            clearable
          />
          <a :href="option.data[item.view || item.prop] || '--'" target="_blank"
            ><span v-if="!option.editStatus && item.inputSet.type === 'link'">{{
              option.data[item.view || item.prop] || '--'
            }}</span></a
          >
          <!--数字输入框-->
          <el-input-number
            v-if="option.editStatus && item.inputSet.type === 'inputNumber'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :max="item.inputSet.max || 999999999999"
            :min="item.inputSet.min || -999999999999"
            :placeholder="item.rules.message"
            :precision="item.inputSet.precision || 0"
            :step="item.inputSet.step || 1"
            :step-strictly="item.inputSet.stepStrictly || false"
            style="width: 100%"
          />
          <span
            v-if="!option.editStatus && item.inputSet.type === 'inputNumber'"
            >{{
              formatNumber(
                option.data[item.view || item.prop],
                item.inputSet.precision || 0,
              ) || '--'
            }}</span
          >
          <!--日期框-->
          <el-date-picker
            v-if="option.editStatus && item.inputSet.type === 'datePicker'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :format="item.inputSet.format || 'YYYY-MM-DD'"
            :placeholder="item.rules.message"
            :type="item.inputSet.datePickerType || 'date'"
            :value-format="item.inputSet.valueFormat || 'YYYY-MM-DD'"
            clearable
          />
          <span
            v-if="!option.editStatus && item.inputSet.type === 'datePicker'"
            >{{ option.data[item.view || item.prop] || '--' }}</span
          >
          <!--下拉框-->
          <el-select
            v-if="option.editStatus && item.inputSet.type === 'select'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :placeholder="item.rules.message"
            clearable
            style="width: 100%"
            @change="changeSelect"
          >
            <el-option
              v-for="item in constants[item.inputSet.source]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span v-if="!option.editStatus && item.inputSet.type === 'select'">{{
            getName(option.data[item.view || item.prop], item.inputSet.source)
          }}</span>
          <!-- 省市区 -->
          <el-cascader
            v-if="option.editStatus && item.inputSet.type === 'cascade'"
            v-model="option.data[item.prop]"
            :options="province"
            size="large"
            style="width: 100%"
          />
          <span v-if="!option.editStatus && item.inputSet.type === 'cascade'">{{
            getProvinces(option.data[item.view || item.prop], '/') || '--'
          }}</span>
          <!--选择对话框-->
          <el-input
            v-if="option.editStatus && item.inputSet.type === 'selectModal'"
            v-model="option.data[item.prop]"
            :disabled="item.disabled || false"
            :placeholder="item.rules.message"
            readonly="readonly"
            @click="showModal(item, item.inputSet.aboutFiled)"
          >
            <template #suffix>
              <el-icon
                class="el-input__icon"
                @click="showModal(item, item.inputSet.aboutFiled)"
              >
                <Edit />
              </el-icon>
            </template>
          </el-input>
          <span
            v-if="!option.editStatus && item.inputSet.type === 'selectModal'"
            >{{ option.data[item.view || item.prop] || '--' }}</span
          >
          <!--对话框-->
          <!--选择坐标-->
          <div
            v-if="option.editStatus && item.inputSet.type === 'selectPosition'"
            :disabled="item.disabled || false"
            style="display: flex; justify-content: space-between; width: 100%"
          >
            <el-input
              v-model="option.data[item.prop]"
              :placeholder="item.rules.message"
              type="textarea"
            />
            <el-button link style="" type="primary" @click="openMap">
              获取坐标
            </el-button>
          </div>
          <div
            v-if="!option.editStatus && item.inputSet.type === 'selectPosition'"
            style="word-break: break-all"
          >
            {{ option.data[item.view || item.prop] || '--' }}
          </div>
          <!--下拉框（树）-->
          <el-tree-select
            v-if="option.editStatus && item.inputSet.type === 'treeSelect'"
            v-model="option.data[item.prop]"
            :data="treeData(item.inputSet.source)"
            :disabled="item.disabled || false"
            :multiple="item.multiple || false"
            :placeholder="item.rules.message"
            :props="item.inputSet.props"
            check-strictly
            default-expand-all
            style="width: 100%"
            @current-change="(event) => onTreeChange(event, item, option.data)"
          />
          <span
            v-if="!option.editStatus && item.inputSet.type === 'treeSelect'"
            >{{ option.data[item.view || item.prop] || '--' }}</span
          >
          <!-- 多图片上传 -->
          <UploadImgs
            v-if="
              option.editStatus && item.inputSet.type === 'equipmentSignageImgs'
            "
            :file-list="JSON.parse(option.data[item.prop] || '[]')"
            :limit="item.inputSet.limit || 10"
            @handle-remove="
              (event) => handleRemove(event, item.prop, item.propList, index)
            "
            @handle-success="
              (event) => handleSuccess(event, item.prop, item.propList, index)
            "
          />
          <div
            v-if="!option.editStatus && item.inputSet.type === 'imgList'"
            class="detail-img-list"
          >
            <div
              v-for="(image, index) in JSON.parse(
                option.data[item.prop] || '[]',
              )"
              :key="index"
              style="height: 100%"
            >
              <img
                :src="image.url"
                alt=""
                title="image.name"
                @click="
                  imgViewVisible = true;
                  imgViewIndex = index;
                  imgViewUrl = JSON.parse(option.data[item.prop] || '[]').map(
                    (item) => {
                      return item.url;
                    },
                  );
                "
              />
            </div>
          </div>
          <!-- 图片上传 -->
          <UploadImg
            v-if="option.editStatus && item.inputSet.type === 'img'"
            v-model:image-url="option.data[item.prop]"
            :file-size="1"
            @handle-success="(event) => imgSuccess(event, item.prop)"
          />
          <UploadImg
            v-if="!option.editStatus && item.inputSet.type === 'img'"
            v-model:image-url="option.data[item.prop]"
            disabled
          />
        </el-form-item>
      </el-descriptions-item>
      <el-descriptions-item
        v-if="item.display && item.inputSet.type === 'none'"
        :key="index"
        :span="item.span || 1"
        class-name="desc-item"
        label-class-name="desc-label"
      />
    </template>
    <slot name="ex"></slot>
    <slot name="Provinces"></slot>
  </el-descriptions>
  <!--  <Map3D ref="mapRef" v-model:showMap="showMap" />-->
  <el-image-viewer
    v-if="imgViewVisible"
    :initial-index="imgViewIndex"
    :url-list="imgViewUrl"
    @close="imgViewVisible = false"
  />
</template>
<style lang="scss">
.cell-item {
  min-width: 120px;
}
</style>
